package middleware

import (
	"main/handlers"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// ProjectRequest 结构体表示通用的项目请求参数
type HostRequest struct {
	HostID                 int    `json:"host_id"`                                  // 项目 ID（可选，删除或更新时需要）
	ProjectId              int    `json:"project_id" binding:"required"`            // 项目名称（必填）
	HostName               string `json:"host_name" binding:"required"`             // 主机名称（必填）
	HostIp                 string `json:"host_ip"`                                  // 主机IP（必填）
	HostCpuArchitecture    string `json:"host_cpu_architecture" binding:"required"` // CPU架构  （必填）
	HostDiskAlarmConfig    string `json:"host_disk_alarm_config"`                   // 绑定主机硬盘指标抓取任务
	HostMemAlarmConfig     string `json:"host_mem_alarm_config"`                    // 绑定主机内存指标抓取任务
	HostCpuAlarmConfig     string `json:"host_cpu_alarm_config"`                    // 绑定主机CPU指标抓取任务
	HostInstruction        string `json:"host_instruction"`                         // 主机备注
	OldHostDiskAlarmConfig string `json:"old_host_disk_alarm_config"`               // 绑定主机硬盘指标抓取任务
	OldHostMemAlarmConfig  string `json:"old_host_mem_alarm_config"`                // 绑定主机内存指标抓取任务
	OldHostCpuAlarmConfig  string `json:"old_host_cpu_alarm_config"`                // 绑定主机CPU指标抓取任务
}

// GetHost 处理获取主机数据的请求
func GetHost(c *gin.Context) {
	// 从请求中获取 project_id 参数
	projectID := c.Query("project_id")

	// 基础查询语句
	query := `
		SELECT a.*, b.project_name, c.code_name FROM hosts a
		LEFT JOIN project b ON a.project_id = b.project_id
		LEFT JOIN sys_code c ON a.host_cpu_architecture = c.code_value AND c.code_parent_type = "device_architecture_type"
		WHERE a.host_del != 1
	`

	// 如果传入了 project_id，则添加过滤条件
	if projectID != "" {
		query += " AND a.project_id = ?"
	}

	// 执行查询
	var results []map[string]interface{}
	var err error
	if projectID != "" {
		results, err = handlers.ExecuteQuery(query, projectID)
	} else {
		results, err = handlers.ExecuteQuery(query)
	}

	// 处理查询结果
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询主机信息失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, results)
}

// PostProjects 处理新建项目的请求
func PostHost(c *gin.Context) {
	var host HostRequest

	if err := c.ShouldBindJSON(&host); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	query := "INSERT INTO hosts (`project_id`, `host_name`, `host_ip`, `host_cpu_architecture`, `host_instruction`, `host_disk_alarm_config`, `host_mem_alarm_config`, `host_cpu_alarm_config`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
	_, err := handlers.ExecuteNonQuery(query, host.ProjectId, host.HostName, host.HostIp, host.HostCpuArchitecture, host.HostInstruction, host.HostCpuAlarmConfig, host.HostMemAlarmConfig, host.HostDiskAlarmConfig)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建主机失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": " 主机创建成功"})
}

// PutProjects 处理更新项目的请求
func PutHost(c *gin.Context) {
	var host HostRequest

	if err := c.ShouldBindJSON(&host); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	if host.HostID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "host ID is required for updates"})
		return
	}

	query := `
		UPDATE hosts
		SET project_id = ?, host_name = ?, host_ip = ?, host_cpu_architecture = ?, host_instruction = ?, host_disk_alarm_config = ?, host_mem_alarm_config = ?, host_cpu_alarm_config = ?
		WHERE host_id = ?
	`
	_, err := handlers.ExecuteNonQuery(query, host.ProjectId, host.HostName, host.HostIp, host.HostCpuArchitecture, host.HostInstruction, host.HostDiskAlarmConfig, host.HostMemAlarmConfig, host.HostCpuAlarmConfig, host.HostID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新主机失败", "details": err.Error()})
		return
	}

	if host.OldHostCpuAlarmConfig != host.HostCpuAlarmConfig && host.OldHostCpuAlarmConfig != "" {
		exec_update_query := `UPDATE alarm_config SET host_id=NULL WHERE  alarm_config_id=?;`
		handlers.ExecuteNonQuery(exec_update_query, host.OldHostCpuAlarmConfig)
	}
	if host.OldHostMemAlarmConfig != host.HostMemAlarmConfig && host.OldHostMemAlarmConfig != "" {
		exec_update_query := `UPDATE alarm_config SET host_id=NULL WHERE  alarm_config_id=?;`
		handlers.ExecuteNonQuery(exec_update_query, host.OldHostMemAlarmConfig)
	}

	if host.OldHostDiskAlarmConfig != host.HostDiskAlarmConfig && host.OldHostDiskAlarmConfig != "" {
		exec_update_query := `UPDATE alarm_config SET host_id=NULL WHERE  alarm_config_id=?;`
		handlers.ExecuteNonQuery(exec_update_query, host.OldHostDiskAlarmConfig)
	}

	c.JSON(http.StatusOK, gin.H{"message": "主机更新成功"})
}

// DeleteProjects 处理删除项目的请求
func DeleteHost(c *gin.Context) {
	var hosts []HostRequest

	if err := c.ShouldBindJSON(&hosts); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid data", "details": err.Error()})
		return
	}

	hostIDs := make([]interface{}, len(hosts))
	placeholders := make([]string, len(hosts))
	for i, host := range hosts {
		if host.HostID == 0 {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Project ID is required for deletion"})
			return
		}
		hostIDs[i] = host.HostID
		placeholders[i] = "?"
	}

	query := `
		UPDATE hosts
		SET host_del = 1
		WHERE host_id IN (` + strings.Join(placeholders, ",") + `)
	`

	_, err := handlers.ExecuteNonQuery(query, hostIDs...)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete projects", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "主机删除成功"})
}
